package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

/**
 * @date: 2025/8/9 15:36
 * @author: yz
 * @version: 1.0
 */
@Service
public class FileUploadServiceImpl  implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties properties;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    @SneakyThrows
    public String fileUpload(MultipartFile file) {
        //校验图片
        BufferedImage read = ImageIO.read(file.getInputStream());
        //判断提示
        if(read==null){
            throw new GuiguException(500,"需要上传图片类型");
        }

        //minio实现保存

        // 判断指定的存储桶是否存在
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
        if (!found) {
            // 如果不存在则创建
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
        }

        //2.1 动态生成上传文件名称 /当日日期/UUID.后缀
        String folderName = "/" + DateUtil.today() + "/";
        String fileName = IdUtil.randomUUID();
        String extName = FileUtil.extName(file.getOriginalFilename());  //
        String objectName = folderName + fileName + "." + extName;


        //文件上传的流上传方式
        minioClient.putObject(
                PutObjectArgs.builder().bucket(properties.getBucketName()).object(objectName).stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());


        //拼接url,并返回

        //http://192.168.254.156:9000/glsx   /2025-06-14/4a857af0-9493-47d6-aae7-683d07af204f.jpg
        String fileUrl=properties.getEndpointUrl()+"/"+properties.getBucketName()+objectName;

        System.out.println(fileUrl);

        return fileUrl;
    }
}
